# @time     :2022/2/24
# @Author   :Simple
# @FileName :driver
import os
import subprocess
import time

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from webdriver_manager.opera import OperaDriverManager

from config import SELENIUM_LOG
from util.logger import log as logger
from util.port import check_port, release_port


class BaseDriver:

    def __init__(self, hub_server, browsers=None, hub_url="127.0.0.1"):
        self.hub_server = hub_server
        if browsers is None:
            self.browsers = [{"name": 'chrome'}]
        else:
            self.browsers = browsers
        self.hub_url = hub_url

    def start_hub(self):
        """
        启动hub
        :return:
        """
        logger.info("start selenium grid server >>>>>>")
        # 开启hub
        hub_cmd = f"java -jar {self.hub_server[0]} -role hub"
        hub_log = "hub_log"+"-"+time.strftime("%Y_%m_%d_%H_%M_%S")+".log"
        hub_out_path = os.path.join(SELENIUM_LOG, hub_log)
        p = subprocess.Popen(hub_cmd, shell=True, stdout=open(hub_out_path, 'a+'), stderr=subprocess.STDOUT)
        return p
        # 读取hub日志，得到hub地址
        # print(f"log file:{hub_out_path}")
        # with open(hub_out_path, 'r', encoding='utf-8') as f:
        #     content = f.readlines()
        # return content

    def start_node(self):
        # 开启node
        cmd = f"-jar {self.hub_server[0]} -role node -nodeConfig {self.hub_server[1]} "
        process_list = []
        # 按浏览器个数开启多个node
        for browser in self.browsers:
            name = browser['name']
            driver = browser['driver']
            path = browser['path']
            if path:
                node_cmd = f"java {driver}={path} " + cmd
            else:
                node_cmd = "java " + cmd
            logger.info(f"start register node: {node_cmd} >>>>")
            log_name = f"node_{name}_log" + "-" + time.strftime("%Y_%m_%d_%H_%M_%S")
            out_path = os.path.join(SELENIUM_LOG, log_name + ".log")
            p = subprocess.Popen(node_cmd, shell=True, stdout=open(out_path, 'a'), stderr=subprocess.STDOUT)
            process_list.append(p)
        return process_list

    def start(self):
        if len(self.hub_server) < 2:
            logger.error(f"没有hub server的jar包或者node json文件")
            return
        if (not os.path.isfile(self.hub_server[0])) or (not os.path.isfile(self.hub_server[1])):
            logger.error(f"没有hub server的jar包或者node json文件")
            return
        # 开启hub
        self.start_hub()
        # 开启node
        self.start_node()

    def get_driver(self):
        """
        启动driver
        :param browser: default 'chrome'
        :return:
        """
        pass

    def close_hub(self):
        if not check_port("127.0.0.1", 4444):
            release_port(4444)

